//
//  IGFindSearchViewController.m
//  iGameApp
//
//  Created by lanou on 16/1/11.
//  Copyright © 2016年 WYC. All rights reserved.
//

#import "IGFindSearchViewController.h"
#import "IGFindSearchCollectionViewCell.h"
#import "IGFindMainTBVModel.h"
#import "IGFindSearchContentTBVController.h"
#import "SearchWordList+CoreDataProperties.h"

@interface IGFindSearchViewController () <UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *searchKeyArray;
@property (nonatomic, strong) IGCustomNavigationController *navc;
@property (nonatomic, strong) IGFindSearchContentTBVController *searchContentVC;
@property (nonatomic, strong) NSMutableArray *searchContentArray;
@property (nonatomic, strong) NSManagedObjectContext *context; // 临时数据库
@property (nonatomic, strong) NSMutableArray *searchWordArray;

@end

@implementation IGFindSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _navc = (IGCustomNavigationController *)self.navigationController;
    
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"TBCell"];
    [_collectionView registerNib:[UINib nibWithNibName:@"IGFindSearchCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CVCell"];
    
    _searchKeyArray = [NSMutableArray array];
    [self requestData];
    
    // 获取appDlegate 把appDelegate的临时数据库赋值给自己的临时数据库
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    _context = delegate.managedObjectContext;
    
    [_searchBar.button addTarget:self action:@selector(searchCancerButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [_searchBar.searchButton addTarget:self action:@selector(searchBarSearchButtonClicked) forControlEvents:(UIControlEventTouchUpInside)];
}

- (void)viewWillAppear:(BOOL)animated
{
    _searchBar.searchButton.userInteractionEnabled = YES;
    _searchBar.textView.delegate = self;
    _searchBar.hidden = NO;
    self.tabBarController.tabBar.hidden = YES;
        [UIView animateWithDuration:.3 animations:^{
            _searchBar.frame = CGRectMake(50, 7, kScreenWidth - 100, 30);
        }];
  // 在视图将要出现时, 读取本地文件刷新搜索记录
    [self searchLocationData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    _searchBar.searchButton.userInteractionEnabled = NO;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.itemSize = CGSizeMake(_collectionView.frame.size.width/3-10, 50);
    _collectionView.collectionViewLayout = flowLayout;
}

- (void)requestData
{
    [IGAFNetworking requestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/gethotkeywords" parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        _searchKeyArray = dataDic[@"data"];
        [_collectionView reloadData];
    } error:^(NSError *requestError) {
        NSLog(@"请求错误");
    }];
}

- (void)requestSearchResultData:(NSString *)searchContent
{ 
    _searchContentArray = [NSMutableArray array];
    NSString *UTFstring = [searchContent stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *urlString = [NSString stringWithFormat:@"http:www.imbatv.cn/api_2_4_0/GetSearchResult?key=%@&num=10&start=0",UTFstring];
    [IGAFNetworking requestWithUrlString:urlString parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        
        if ([dataDic[@"message"] isEqualToString:@"没有查询数据"]) {
            [_searchContentVC addTableViewHeadView];
            [_searchContentVC.tableView.mj_header endRefreshing];
       //     [_searchContentVC.tableView reloadData];
            return;
        }else{
            _searchContentVC.titleLabel.frame = CGRectZero;
        }
        
        for (NSDictionary *dic in dataDic[@"data"]) {
            // 共用主页面tableView的model
            IGFindMainTBVModel *model = [[IGFindMainTBVModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_searchContentArray addObject:model];
        }
        _searchContentVC.dataArray = _searchContentArray;
        // 结束刷新
        [_searchContentVC.tableView.mj_header endRefreshing];
        [_searchContentVC.tableView reloadData];
    } error:^(NSError *requestError) {
        
    }];
}

- (IBAction)clearSearchData:(id)sender {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"SearchWordList" inManagedObjectContext:_context];
    [fetchRequest setEntity:entity];
    NSError *error = nil;
    NSArray *fetchedObjects = [_context executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"请求失败");
    }
    for (SearchWordList *searchWorld in fetchedObjects) {
        [_context deleteObject:searchWorld];
    }
    [_searchWordArray removeAllObjects];
    [_context save:nil];
    [_tableView reloadData];
}

#pragma mark  --  UITableView 代理和数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_searchWordArray.count > 6) {
        return 6;
    }
    return _searchWordArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TBCell"];
    SearchWordList *searchWorld = _searchWordArray[indexPath.row];
    cell.textLabel.text = searchWorld.searchWord;
    cell.backgroundColor = tableView.backgroundColor;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchWordList *searchWorld = _searchWordArray[indexPath.row];
    _searchBar.textView.text = searchWorld.searchWord;
    [self accordingWordSearchAndJumpContentVC];
}

#pragma mark  --  UICollectionView 代理和数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _searchKeyArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    IGFindSearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CVCell" forIndexPath:indexPath];
    cell.label.text = _searchKeyArray[indexPath.row][@"search_key"];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    _searchBar.textView.text = _searchKeyArray[indexPath.row][@"search_key"];
    [self accordingWordSearchAndJumpContentVC];
}

// searchBar
- (void)searchCancerButtonClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:NO];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self accordingWordSearchAndJumpContentVC];
    return YES;
}

- (void)searchBarSearchButtonClicked
{
    [self accordingWordSearchAndJumpContentVC];
}



// 输入搜索内容跳转 跳转页面
- (void)accordingWordSearchAndJumpContentVC
{
    if (_searchBar.textView.text.length == 0 || [_searchBar.textView.text isEqualToString:@" "] || [_searchBar.textView.text isEqualToString:@"  "]) {
        return;
    }
    [self searchLocationData];
    for (SearchWordList *search in _searchWordArray) {
        if ([search.searchWord isEqualToString:_searchBar.textView.text]) {
            [_context deleteObject:search];
        }
    }
    SearchWordList *searchWord = [NSEntityDescription insertNewObjectForEntityForName:@"SearchWordList" inManagedObjectContext:_context];
    searchWord.searchWord = _searchBar.textView.text;
    [_context save:nil];
    
       // 初始化搜索完展示内容的VC
    _searchContentVC = [[IGFindSearchContentTBVController alloc] init];
    _searchContentVC.pushHere = SearchVCPush;
    // 下拉刷新
     _searchContentVC.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requestSearchResultData:_searchBar.textView.text];
    }];
    [_searchBar endEditing:YES];
    [_searchContentVC.tableView.mj_header beginRefreshing];
 //   [_searchBar setShowsCancelButton:YES animated:YES];
    [self.navigationController pushViewController:_searchContentVC animated:NO];
}

// 查找本地数据库的搜索记录
- (void)searchLocationData
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"SearchWordList" inManagedObjectContext:_context];
    [fetchRequest setEntity:entity];
    NSError *error = nil;
    NSArray *fetchedObjects = [_context executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"请求失败");
    }
    // 反向加入. 展示数据
    _searchWordArray = [NSMutableArray array];
    for (NSInteger i = (fetchedObjects.count - 1); i >= 0; i--) {
        [_searchWordArray addObject:fetchedObjects[i]];
    }
    [_tableView reloadData];
}

// 取消第一响应者
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_searchBar endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
